/**
 * 游戏数据管理
 */
const GameData = {
    // 游戏状态数据
    gameState: {
        currentYear: 0,
        bossCountdown: CONFIG.BOSS.FIRST_ATTACK,
        currentPlane: 1,
        gameSpeed: CONFIG.GAME_SPEED.PAUSED,
        lastUpdateTime: 0
    },
    
    // 地图数据
    map: {
        terrain: [], // 二维数组，存储地形类型
        resourcePoints: [], // 资源点坐标数组 [{x, y}, ...]
        dangerZones: [], // 危险区域坐标数组 [{x, y}, ...]
        viewportOffset: { x: 0, y: 0 },
        zoom: 1
    },
    
    // 种族数据
    races: [], // 当前游戏中的种族
    
    // 王国数据
    kingdoms: [], // 王国数组
    
    // NPC数据
    npcs: [], // NPC数组
    
    // 强者榜数据
    strongestList: [], // 当前强者榜
    historicalHeroes: [], // 历史强者记录
    
    // 魔王数据
    boss: {
        name: "",
        ability: 0,
        weakness: null // {raceId: 1, effect: -0.2} 表示对精灵族伤害-20%
    },
    
    // 失败计数器
    bossFailures: 0,
    
    /**
     * 初始化游戏数据
     */
    initialize() {
        // 重置游戏状态
        this.resetGameState();
        
        // 生成地图
        this.generateMap();
        
        // 选择种族
        this.selectRaces();
        
        // 创建王国
        this.createKingdoms();
        
        // 生成初始NPC
        this.generateInitialNPCs();
        
        // 更新强者榜
        this.updateStrongestList();
        
        // 生成魔王数据
        this.generateBoss();
        
        console.log("游戏数据初始化完成");
    },
    
    /**
     * 重置游戏状态
     */
    resetGameState() {
        this.gameState = {
            currentYear: 0,
            bossCountdown: CONFIG.BOSS.FIRST_ATTACK,
            currentPlane: 1,
            gameSpeed: CONFIG.GAME_SPEED.PAUSED,
            lastUpdateTime: Date.now()
        };
        
        this.map = {
            terrain: [],
            resourcePoints: [],
            dangerZones: [],
            viewportOffset: { x: 0, y: 0 },
            zoom: 1
        };
        
        this.races = [];
        this.kingdoms = [];
        this.npcs = [];
        this.strongestList = [];
        this.historicalHeroes = [];
        
        this.boss = {
            name: "",
            ability: 0,
            weakness: null
        };
    },
    
    /**
     * 生成游戏地图
     */
    generateMap() {
        const width = CONFIG.MAP.WIDTH;
        const height = CONFIG.MAP.HEIGHT;
        
        // 初始化地形二维数组
        this.map.terrain = Array(height).fill().map(() => Array(width).fill(null));
        
        // 生成地形
        for (let y = 0; y < height; y++) {
            for (let x = 0; x < width; x++) {
                // 使用柏林噪声或简单随机来生成地形
                const random = Math.random();
                let terrainType;
                
                if (random < CONFIG.MAP.TERRAIN_TYPES.PLAINS.probability) {
                    terrainType = 'PLAINS';
                } else if (random < CONFIG.MAP.TERRAIN_TYPES.PLAINS.probability + CONFIG.MAP.TERRAIN_TYPES.MOUNTAINS.probability) {
                    terrainType = 'MOUNTAINS';
                } else if (random < CONFIG.MAP.TERRAIN_TYPES.PLAINS.probability + CONFIG.MAP.TERRAIN_TYPES.MOUNTAINS.probability + CONFIG.MAP.TERRAIN_TYPES.FOREST.probability) {
                    terrainType = 'FOREST';
                } else {
                    terrainType = 'DESERT';
                }
                
                this.map.terrain[y][x] = terrainType;
            }
        }
        
        // 生成资源点
        const resourcePointCount = Math.floor(width * height * CONFIG.MAP.RESOURCE_DENSITY);
        for (let i = 0; i < resourcePointCount; i++) {
            const x = Utils.randomInt(0, width - 1);
            const y = Utils.randomInt(0, height - 1);
            this.map.resourcePoints.push({ x, y });
        }
        
        // 生成危险区域
        const dangerZoneCount = Math.floor(width * height * CONFIG.MAP.DANGER_DENSITY);
        for (let i = 0; i < dangerZoneCount; i++) {
            const x = Utils.randomInt(0, width - 1);
            const y = Utils.randomInt(0, height - 1);
            this.map.dangerZones.push({ x, y });
        }
        
        console.log(`地图生成完成: ${width}x${height}, 资源点: ${this.map.resourcePoints.length}, 危险区域: ${this.map.dangerZones.length}`);
    },
    
    /**
     * 从预设种族中随机选择5个
     */
    selectRaces() {
        this.races = Utils.randomSample(CONFIG.RACES, 5);
        console.log("已选择种族:", this.races.map(race => race.name).join(", "));
    },
    
    /**
     * 为每个种族创建王国
     */
    createKingdoms() {
        this.kingdoms = [];
        
        // 为每个种族创建一个王国
        this.races.forEach(race => {
            // 寻找合适的初始位置（避免重叠）
            let location = this.findSuitableLocation();
            
            // 生成随机的初始人口
            const initialPopulation = Utils.randomInt(
                CONFIG.KINGDOM.INITIAL_POPULATION.MIN,
                CONFIG.KINGDOM.INITIAL_POPULATION.MAX
            );
            
            // 创建王国
            const kingdom = {
                id: Utils.generateId(),
                raceId: race.id,
                name: Utils.generateRandomName('kingdom', race.id),
                foundYear: this.gameState.currentYear,
                resources: initialPopulation * CONFIG.KINGDOM.RESOURCE_GENERATION.PER_POPULATION,
                military: initialPopulation * CONFIG.KINGDOM.MILITARY_GENERATION.PER_POPULATION,
                population: initialPopulation,
                location: location,
                status: "繁荣",
                color: race.color
            };
            
            this.kingdoms.push(kingdom);
            console.log(`创建王国: ${kingdom.name}, 种族: ${race.name}, 初始人口: ${kingdom.population}`);
            this.logChronicleEvent("KINGDOM_FOUNDED", `王国 ${kingdom.name} (${race.name}) 建立于 ${kingdom.foundYear} 年，初始人口 ${kingdom.population}`);
        });
    },
    
    /**
     * 寻找适合王国的初始位置
     * @returns {{x: number, y: number}} 坐标
     */
    findSuitableLocation() {
        const width = CONFIG.MAP.WIDTH;
        const height = CONFIG.MAP.HEIGHT;
        const minDistance = 200; // 王国之间的最小距离
        
        let attempts = 0;
        const maxAttempts = 100;
        
        while (attempts < maxAttempts) {
            // 生成随机位置，避开地图边缘
            const x = Utils.randomInt(100, width - 100);
            const y = Utils.randomInt(100, height - 100);
            
            // 检查是否与现有王国距离过近
            let tooClose = false;
            for (const kingdom of this.kingdoms) {
                const distance = Math.sqrt(
                    Math.pow(kingdom.location.x - x, 2) + 
                    Math.pow(kingdom.location.y - y, 2)
                );
                
                if (distance < minDistance) {
                    tooClose = true;
                    break;
                }
            }
            
            // 如果位置合适，返回
            if (!tooClose) {
                return { x, y };
            }
            
            attempts++;
        }
        
        // 如果尝试多次仍找不到合适位置，返回一个随机位置
        return {
            x: Utils.randomInt(100, width - 100),
            y: Utils.randomInt(100, height - 100)
        };
    },
    
    /**
     * 生成初始NPC
     */
    generateInitialNPCs() {
        this.npcs = [];
        
        // 为每个王国生成初始NPC
        this.kingdoms.forEach(kingdom => {
            const race = this.getRaceById(kingdom.raceId);
            const npcCount = Math.floor(kingdom.population / CONFIG.NPC.GENERATION_RATE);
            
            for (let i = 0; i < npcCount; i++) {
                this.generateNPC(kingdom.raceId);
            }
        });
        
        console.log(`初始NPC生成完成，共${this.npcs.length}个`);
    },
    
    /**
     * 生成一个NPC
     * @param {number} raceId - 种族ID
     * @returns {Object} 生成的NPC对象
     */
    generateNPC(raceId) {
        const race = this.getRaceById(raceId);
        let ability;
        
        // 检查是否生成传说级NPC
        if (race.legendaryChance && Utils.chance(race.legendaryChance)) {
            ability = Utils.randomInt(
                race.legendaryAbilityRange[0],
                race.legendaryAbilityRange[1]
            );
            this.logChronicleEvent("LEGENDARY_HERO", `传说级强者 ${npc.name} (${race.name}) 诞生于 ${npc.birthYear} 年，能力值 ${ability}`);
        } else {
            ability = Utils.randomInt(
                race.npcAbilityRange[0],
                race.npcAbilityRange[1]
            );
        }
        
        const npc = {
            id: Utils.generateId(),
            raceId: raceId,
            name: Utils.generateRandomName('npc', raceId),
            ability: ability,
            birthYear: this.gameState.currentYear,
            status: "存活",
            deathYear: null
        };
        
        this.npcs.push(npc);
        return npc;
    },
    
    /**
     * 更新强者榜
     */
    updateStrongestList() {
        // 筛选出存活的NPC
        const aliveNPCs = this.npcs.filter(npc => npc.status === "存活");
        
        // 按能力值排序
        const sorted = [...aliveNPCs].sort((a, b) => b.ability - a.ability);
        
        // 取前100名
        this.strongestList = sorted.slice(0, 100).map((npc, index) => ({
            rank: index + 1,
            npc: npc
        }));
    },
    
    /**
     * 记录编年史事件
     * @param {string} eventType - 事件类型
     * @param {string} description - 事件描述
     */
    logChronicleEvent(eventType, description) {
        const timestamp = new Date().toISOString();
        const logEntry = `[${timestamp}] [${eventType}] ${description}\n`;
        
        // 获取当前回合和年份
        const round = this.gameState.currentPlane;
        const year = this.gameState.currentYear;
        
        // 追加到日志文件，自动处理文件大小限制
        Utils.appendToLogFile(logEntry, round, year);
    },
    
    /**
     * 生成魔王数据
     */
    generateBoss() {
        const bossNames = [
            "暗影之王", "深渊魔主", "混沌使者", "末日预言者", "虚空吞噬者",
            "灭世者", "永恒梦魇", "血月主宰", "死亡编织者", "黑暗收割者"
        ];
        
        const bossWeaknesses = [
            { raceId: 1, effect: -0.2 }, // 对精灵族伤害-20%
            { raceId: 2, effect: -0.15 }, // 对兽人族伤害-15%
            { raceId: 3, effect: -0.25 }, // 对矮人族伤害-25%
            { raceId: 4, effect: -0.1 }, // 对人族伤害-10%
            { raceId: 5, effect: -0.3 } // 对亡灵族伤害-30%
        ];
        
        const bossImages = [
            "https://example.com/boss1.jpg",
            "https://example.com/boss2.jpg",
            "https://example.com/boss3.jpg",
            "https://example.com/boss4.jpg",
            "https://example.com/boss5.jpg"
        ];
        
        this.boss = {
            name: bossNames[Utils.randomInt(0, bossNames.length - 1)],
            ability: 0, // 将在挑战时计算
            weakness: bossWeaknesses[Utils.randomInt(0, bossWeaknesses.length - 1)],
            image: bossImages[Utils.randomInt(0, bossImages.length - 1)]
        };
    },
    
    /**
     * 根据ID获取种族
     * @param {number} id - 种族ID
     * @returns {Object|null} 种族对象或null
     */
    getRaceById(id) {
        return this.races.find(race => race.id === id) || null;
    },
    
    /**
     * 获取游戏总览数据
     * @returns {Object} 游戏总览数据
     */
    getOverviewData() {
        // 计算总人口
        const totalPopulation = this.kingdoms.reduce((sum, kingdom) => sum + kingdom.population, 0);
        
        // 计算总资源
        const totalResources = this.kingdoms.reduce((sum, kingdom) => sum + kingdom.resources, 0);
        
        // 计算总军事力量
        const totalMilitary = this.kingdoms.reduce((sum, kingdom) => sum + kingdom.military, 0);
        
        // 计算强者数量
        const totalHeroes = this.npcs.filter(npc => npc.status === "存活").length;
        
        return {
            totalPopulation,
            totalResources,
            totalMilitary,
            totalHeroes
        };
    },
    
    /**
     * 保存当前游戏状态
     * @param {string} slotName - 存档槽名称
     * @returns {boolean} 是否保存成功
     */
    saveGameState(slotName) {
        const saveData = {
            gameState: this.gameState,
            map: this.map,
            races: this.races,
            kingdoms: this.kingdoms,
            npcs: this.npcs,
            strongestList: this.strongestList,
            historicalHeroes: this.historicalHeroes,
            boss: this.boss,
            timestamp: Date.now()
        };
        
        console.log(`[存档] 年份: ${this.gameState.currentYear}, 存档槽: ${slotName}`);
        return Utils.saveGame(slotName, saveData);
    },
    
    /**
     * 将内容追加到文件
     * @param {string} filePath - 文件路径
     * @param {string} content - 追加的内容
     */
    appendToFile(filePath, content) {
        const fs = require('fs');
        fs.appendFileSync(filePath, content, 'utf8');
    },
    
    /**
     * 追加日志内容，自动处理文件大小限制
     * @param {string} content - 日志内容
     * @param {number} round - 当前回合
     * @param {number} year - 当前年份
     */
    appendToLogFile(content, round, year) {
        const fs = require('fs');
        const path = require('path');
        
        // 日志目录
        const logDir = path.join(__dirname, '..', 'logs');
        if (!fs.existsSync(logDir)) {
            fs.mkdirSync(logDir);
        }
        
        // 查找当前日志文件
        let currentLogFile = '';
        const files = fs.readdirSync(logDir);
        const logPattern = /^(\d+)_(\d+)_(\d+)_(\d+)\.log$/;
        
        // 按修改时间排序，获取最新的日志文件
        const sortedFiles = files
            .filter(file => logPattern.test(file))
            .sort((a, b) => {
                const statA = fs.statSync(path.join(logDir, a));
                const statB = fs.statSync(path.join(logDir, b));
                return statB.mtimeMs - statA.mtimeMs;
            });
        
        if (sortedFiles.length > 0) {
            currentLogFile = sortedFiles[0];
            const filePath = path.join(logDir, currentLogFile);
            const stats = fs.statSync(filePath);
            
            // 检查文件大小是否超过20MB
            if (stats.size + content.length > 20 * 1024 * 1024) {
                currentLogFile = ''; // 需要创建新文件
            }
        }
        
        // 创建新日志文件
        if (!currentLogFile) {
            const now = new Date();
            const dateStr = now.toISOString().split('T')[0].replace(/-/g, '');
            const timeStr = now.toTimeString().split(' ')[0].replace(/:/g, '');
            currentLogFile = `${round}_${year}_${dateStr}_${timeStr}.log`;
        }
        
        // 追加日志内容
        const filePath = path.join(logDir, currentLogFile);
        fs.appendFileSync(filePath, content, 'utf8');
    },
    
    /**
     * 加载游戏状态
     * @param {string} slotName - 存档槽名称
     * @returns {boolean} 是否加载成功
     */
    loadGameState(slotName) {
        const saveData = Utils.loadGame(slotName);
        
        if (!saveData) {
            console.log(`[加载失败] 存档槽: ${slotName}`);
            return false;
        }
        
        console.log(`[加载成功] 年份: ${saveData.gameState.currentYear}, 存档槽: ${slotName}`);
        
        this.gameState = saveData.gameState;
        this.map = saveData.map;
        this.races = saveData.races;
        this.kingdoms = saveData.kingdoms;
        this.npcs = saveData.npcs;
        this.strongestList = saveData.strongestList;
        this.historicalHeroes = saveData.historicalHeroes;
        this.boss = saveData.boss;
        
        return true;
    }
};